package com.java.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.mapper.MessageMapper;
import com.java.po.Message;
import com.java.po.MessageMap;
import com.java.service.MessageService;
import com.java.tool.AjaxJson;

/**
 * Title:MessageServiceImpl.java
 * Description:
 * @author:sprogrammer
 * @time:2018年2月23日下午8:54:56
 */
public class MessageServiceImpl implements MessageService {
	@Autowired
	private MessageMapper messageMapper;
	private AjaxJson ajaxJson;
	
	@SuppressWarnings("resource")
	public MessageServiceImpl(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
		messageMapper = (MessageMapper) applicationContext.getBean("messageMapper");		
		ajaxJson = new AjaxJson();
	}
	
	public void cleanAjaxJson(){
		ajaxJson.setData("");
		ajaxJson.setTotal(0);
		ajaxJson.setMessage("");
	}
	
	@Override
	public AjaxJson deleteMessage(Message message) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		int flag = messageMapper.deleteMessage(message);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson insertMessage(Message message) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根\
		int flag = messageMapper.insertMessage(message);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson updateMessageByMessageid(Message message) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		int flag = messageMapper.updateMessageByMessageid(message);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson findAllMessage(MessageMap messageMap) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		Message message = new Message();
		int page = messageMap.getPage();
		int pageSize = messageMap.getPageSize();
		if(messageMap.getMessage()!=null){
			message = messageMap.getMessage();
		}
		PageHelper.startPage(page,pageSize);
		List<Message> list = messageMapper.findAllMessage(message);
		PageInfo<Message> pageInfo = new PageInfo<>(list);
		ajaxJson.setData(pageInfo.getList());
		ajaxJson.setTotal((int)pageInfo.getTotal());
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson findMessageByid(Message message) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		message = messageMapper.findMessageByid(message);
		ajaxJson.setData(message);
		ajaxJson.setMessage("success");
		ajaxJson.setTotal(1);
		return ajaxJson;
	}

}
